package com.leetcode.partition6;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author `RKC`
 * @date 2021/11/20 9:08
 */
public class LC594最长和谐子序列 {

    public static int findLHS(int[] nums) {
        return slidingWindow(nums);
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, 2, 2, 5, 2, 3, 7};
//        int[] nums = {1, 1, 1, 1};
        System.out.println(findLHS(nums));
    }

    private static int slidingWindow(int[] nums) {
        int answer = 0;
        //排序预处理
        Arrays.sort(nums);
        for (int left = 0, right = 0; right < nums.length; right++) {
            //经过排序处理，所有连续数字都在一起
            while (left < right && nums[right] - nums[left] > 1) left++;
            if (nums[right] - nums[left] == 1) answer = Math.max(answer, right - left + 1);
        }
        return answer;
    }

    private static int hashTable(int[] nums) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int num : nums) {
            count.put(num, count.getOrDefault(num, 0) + 1);
        }
        int answer = 0;
        for (int num : nums) {
            if (count.containsKey(num - 1)) {
                answer = Math.max(answer, count.get(num) + count.get(num - 1));
            }
        }
        return answer;
    }
}
